package at.irian.jsfatwork.web.model;

import at.irian.jsfatwork.domain.BaseEntity;
import at.irian.jsfatwork.web.model.DetailListBean;

import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.context.FacesContext;
import javax.faces.component.UIComponent;

/**
 * @author Thomas Spiegl, IRIAN Solutions GmbH
 */
public class EntityConverter  implements Converter {
    private Class clazz;
    private String beanName;

    public EntityConverter(Class clazz, String beanName) {
        this.clazz = clazz;
        this.beanName = beanName;
    }

    public Object getAsObject(FacesContext context, UIComponent component, String value) throws ConverterException {
        if (value == null || value.length() == 0) {
            return null;
        }
        FacesContext ctx = FacesContext.getCurrentInstance();
        // resolve bean in order to activate interceptors (need tx-interceptor!)
        return ((DetailListBean)ctx.getApplication().getVariableResolver().resolveVariable(ctx, this.beanName))
                .findEntity(this.clazz, new Long(value));
    }

    public String getAsString(FacesContext context, UIComponent component, Object value) throws ConverterException {
        if (value == null)
            return "";
        Long id = ((BaseEntity) value).getId();
        return id != null ? id.toString() : null;
    }
}
